function out=sine(nbits, npts, fs, fsin, level, dither)
% sine wave generator. output scaled to [-1 1]
% nbits  : 2^nbits quantization depth. < 1 for real wave.
% npts   : output vector length
% fs     : sampling frequency
% fsin   : sine frequency
% level  : sine amplitude ]0,1]
% dither : number of dither bits. 0 for no dither.

% 
% Dithered sine generation process: 
% - build a (nbits+dither) quantized sine
% - add a random noise on the (dither) lsb bits
% - truncate to nbits

out = zeros(1,npts);
out = level*sin(2*pi*fsin/fs*[0:npts-1]);

if (dither == 0)
    if (nbits == 1)
        for i=1:npts
            if out(1,i) > 0
                out(1,i) = 1;
            else 
                out(1,i) = -1;
            end
        end
    elseif (nbits > 1)
        q = 2^(nbits-1)-1;
        out = floor(out.*q);
    end
else
    q = 2^(nbits-1+dither)-1;
    out = floor(out.*q);
    if (dither == 1)
        d = 2*floor(rand(1,npts)-0.5)+1;
        out = out + d;
    else
        d = floor((rand(1,npts)-0.5)*2^dither);
        out=out+d;
    end
    out = out./2^dither;
end

if (nbits > 1)
    q = 2^(nbits-1)-1;
    out = out./q;
end
    
    

        
    



